import Vue from 'vue'
import axios from 'axios'
import router from '../router'
const errorFn = err => {
    if (err.toString().indexOf('timeout') != -1) {
        Vue.prototype.$message.error('请求超时，请稍后再试')
    }
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.message = '未登录，请登录'
                router.push({
                    path: '/login'
                })
                break

            case 403:
                err.message = '请求无权限~'
                break

            case 404:
                err.message = '接口走丢啦~'
                break

            case 500:
                err.message = '执行失败，请检测网络后再次尝试'
                break

            case 502:
                err.message = '服务器繁忙，请检测网络后再次尝试'
                break

            case 503:
                err.message = '服务器繁忙，请检测网络后再次尝试'
                break

            case 505:
                err.message = 'HTTP版本不受支持'
                break

            default:
                err.message = '请求失败，请稍后再试'
        }
        Vue.prototype.$message.error(err.message)
    }
    return Promise.reject(err)
}
const $http = axios.create({
    headers: {},
    baseURL: process.env.NODE_ENV === "development" ? "/api" : 'http://wechat1.cd1a.cn/',
    timeout: 60000,
    withCredentials: true
})


$http.interceptors.response.use(
    response => {
        if (response.data.result_code === 200) {
            return response.data;
        } else {
            if (response.data.result_code === 400) {
                Vue.prototype.$message.error('未授权，请登录')
                router.push({
                    path: '/login'
                })
            } else {
                if (response.data.result_code != 1001 && response.data.result_code != 3001) {
                    // Vue.prototype.$message.error(response.data.message)
                }
                return response.data
            }
        }
    }, errorFn
)
Vue.prototype.$http = $http
export default $http